import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from 'view/user/login'
import HomeLayout from '@/layouts/HomeLayout'
import NotFound from 'view/404'
import Welcome from 'view/welcome'
import Users from 'view/user/users'
import RoleList from 'view/rights/roleList'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    name: 'login',
    path: '/login',
    component: Login,
  },
  {
    name: 'HomeLayout',
    path: '/',
    component: HomeLayout,
    redirect: '/welcome',
    children: [
      {
        name: 'welcome',
        path: '/welcome',
        component: Welcome,
      },
      {
        name: 'users',
        path: '/users',
        component: Users,
      },
      {
        name: 'roles',
        path: '/roles',
        component: RoleList,
      },
      {
        name: 'rights',
        path: '/rights',
        component: () => import('view/rights/list')
      },
      {
        name: 'goods',
        path: '/goods',
        component: () => import('view/goods/list')
      },
      {
        name: 'params',
        path: '/params',
        component: () => import('view/goods/params')
      },
      {
        name: '404',
        path: '*',
        component: NotFound,
      },

    ]
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const token = store.getters.token;
  const isLogin = to.name === 'login'
  //如果有token，并且在登录页，那么跳转到首页
  if (token && isLogin) {
    return next({ name: 'HomeLayout' });
  }
  //如果没有token，并且不是在登录页，那么跳转到登录页
  if (!token && !isLogin) {
    return next({ name: 'login' });
  }
  next()
})


export default router
